layui.define(['table', 'treeTable', 'tableSelect', 'laydate'], function (exports) {

    var $ = layui.$
        , form = layui.form
        , table = layui.table
        , setter = layui.setter
        , admin = layui.admin
        , tableSelect = layui.tableSelect
        , laydate = layui.laydate
        , treeTable = layui.treeTable;

    var colsArr;
    var tableTitle;//表头标题
    var tableField;//表头标题 有隐藏
    var tableHead;//表头字段
    var tableSearch = {};//全局搜索条件

    var id;
    var goodscode = $('#goodscode', parent.document).val();


    layui.laydate.render({
        elem: '#startdateLayDate' //指定元素
        , trigger: 'click'
    });

    layui.laydate.render({
        elem: '#enddateLayDate' //指定元素
        , trigger: 'click'
    });

    hiddendiv();

    function hiddendiv() {
        $("#table").show();
        $("#form").hide();
        loadtable();
    }

    function showdiv() {
        $("#table").hide();
        $("#form").show();
    }

    var parentJson = {};
    var obj = {
        setParentJson: function setParentJson(json) {
            parentJson = json;
            load();
        }
    }



    function loadtable() {
        colsArr = [
            {field: 'goodscode',hide:true, title: '所属系统', sort: false},
            {field: 'system',hide:true, title: '所属系统', sort: false},
            {field: 'systemname', title: '所属系统',width:100, sort: false},
            {
                field: 'orderType', title: '订货方式',width:100, sort: false, templet: function (d) {
                    if (d.system.toString() == "0") {
                        return "手动订货"
                    } else {
                        return "自动订货"
                    }
                }
            },
            {field: 'oplvalue', title: 'OPL系数',width:100, sort: false},
            {
                field: 'orderintype', title: '补货方式',width:100, sort: false, templet: function (d) {
                    if (d.orderintype.toString() == "1") {
                        return "按参数补货"
                    } else if (d.orderintype.toString() == "2") {
                        return "按前四周销售补"
                    } else if (d.orderintype.toString() == "3") {
                        return "按昨日销售补"
                    } else {
                        return "按台账图陈列量补";
                    }
                }
            },
            {field: 'safestock', title: '安全天数',width:100, sort: false},
            {field: 'minday', title: '最小到货天数', width:100,sort: false},
            {field: 'startdate', title: '入场日期', width:100,sort: false},
            {field: 'enddate', title: '出场日期', width:100,sort: false},
            {
                field: 'attribute', title: '属性',width:100, sort: false, templet: function (d) {
                    if (d.system.toString() == "0") {
                        return "可订货"
                    } else {
                        return "可退货"
                    }
                }
            },
            {
                field: 'flag', title: '状态', width:100,sort: false, templet: function (d) {
                    if (d.system.toString() == "0") {
                        return "启用"
                    } else {
                        return "禁用"
                    }
                }
            },
            {field: 'remark', title: '备注',width:100, sort: false},
            {fixed: 'right', title: '操作', width: 70, toolbar: '#opeTable'}
        ];

        layui.each(colsArr, function (inx, val) {
            tableHead += val.hasOwnProperty('field') ? val.field : '-';
            tableHead += ',';
            tableTitle += val.hasOwnProperty('title') ? (val.hide ? '' : val.title + ',') : ',';
            tableField += val.hasOwnProperty('field') ? (val.hide ? '' : val.field + ',') : ',';
        })
        //tableHead是获取表字段
        tableHead = tableHead.substring(tableHead.indexOf(',') + 1, tableHead.length - 1);
        //导出时需要用到标题
        tableTitle = tableTitle.substring(tableTitle.indexOf(',') + 1, tableTitle.length - 1);
        //导出需要用到实际导出的字段
        tableField = tableField.substring(tableField.indexOf(',') + 1, tableField.length - 1);
        tableSearch["goodscode"] = goodscode;
        //用户管理
        table.render({
            elem: '#goods_order_table'
            , url: setter.host + '/goods_order/getSelectSystem'
            , cols: [colsArr]
            //,toolbar: 'true'
            //,defaultToolbar: ['print']
            , method: 'post'
            , contentType: 'application/json; charset=utf-8'
            , where: { //请求参数（注意：这里面的参数可任意定义，并非下面固定的格式）
                search: tableSearch //查询字段
                , headField: tableHead //表头字段
            }
            , page: true
            , limit: 10
            , limits: [10, 20, 30]
            , height: '640'
            , text: {
                none: '暂无相关数据'
            }
        });
    }

    function load() {
        addByFilling();
    }

    function addByFilling() {
        layui.admin.req({
            url: layui.setter.host + '/goods_order/fillAdd'
            , type: 'post'
            , dataType: 'json'
            , contentType: "application/json; charset=utf-8"
            , data: JSON.stringify(parentJson)
            , done: function (res) {
                //请求成功后
                if (res.status == 1000) {
                    layer.msg(res.msg);
                } else {
                    //先填充complexselect的下拉框
                    layui.each(res.data.select, function (inx, val) {
                        layui.each(val, function (inxSub, valSub) {
                            $("select[name='" + inx + "']").append('<option value="' + valSub.value1 + '">' + valSub.key1 + '</option>');
                            form.render('select');
                        })
                    });
                    form.val('form1', res.data.field);
                }
            }
        });
    }

    function editByFilling() {

        $('#goodsnameTableSelect').val(parentJson.goodsname)
        //编辑填充
        layui.admin.req({
            url: layui.setter.host + '/goods_order/fillEdit'
            , type: 'post'
            , dataType: 'json'
            , contentType: "application/json; charset=utf-8"
            , data: JSON.stringify(parentJson)
            , done: function (res) {
                //请求成功后
                if (res.status == setter.response.statusCode.status_Success) {
                    //先填充complexselect的下拉框
                    layui.each(res.data.select, function (inx, val) {
                        layui.each(val, function (inxSub, valSub) {
                            $("select[name='" + inx + "']").append('<option value="' + valSub.value1 + '">' + valSub.key1 + '</option>');
                            form.render('select');
                        })
                    });
                    layui.each(res.data.field, function (inx, val) {
                        if (inx == 'goodsname') {
                            $('#goodsnameTableSelect').attr('ts-selected', val)
                        }
                    });
                    form.val('form1', res.data.field);
                    $('select[name="system"]').find('option').each(function (inx) {
                        if (parentJson.goodscode == $(this).text()) {
                            form.val('form1', {
                                "system": $(this).val()
                            });
                        }
                    })


                } else {
                    layer.msg(res.msg);
                }
            }
        });
        form.val('form1', {
            "goodscode": parentJson.goodscode
        });
    }

//	------------------------------------------------------------------------------------------- 	
    var roleTable = treeTable.render({
        elem: '#LAY-role-list',
        tree: {
            iconIndex: 1,  // 折叠图标显示在第几列
            idName: 'id'  // 自定义id字段的名称
            , arrowType: 'arrow1' //箭头类型
        },
        parent_key: 'fatherid',
        height: '600',
        cols: colsArr = [
            {field: 'id', title: 'id', hide: true},
            {field: 'name', title: '名称'},

        ],
        method: 'post',
        contentType: "application/json; charset=utf-8",
        url: setter.host + '/unite_platform/goods_order/roleList'
    });

    table.on('tool(goods_order_table)', function (obj) {
        var data = obj.data;
        if (obj.event === 'del') {
            layer.confirm('确认删除该行么', function (index) {
                // console.log("test")
                data.flag = 1;
                layui.admin.req({
                    url: layui.setter.host+'/goods_order/getSelectSystemDel'
                    ,type:'post'
                    ,dataType:'json'
                    ,contentType: "application/json; charset=utf-8"
                    ,data:JSON.stringify(data)
                    ,done: function(res){
                        //请求成功后
                        table.reload('goods_order_table');
                        // if(res.status==setter.response.statusCode.status_Success){
                        //
                        //     //     layer.msg(res.msg);
                        // //     // obj.del(); //删除对应行（tr）的DOM结构，并更新缓存
                        // }
//									table.render();
                    }
                });

                layer.close(index);
            });
        }
    });


    table.on('row(goods_order_table)', function(obj){
        id = obj.data.system;
        var delId = {};
        delId.id = obj.data.system;
        layui.admin.req({
            url: layui.setter.host + '/goods_system_supplier/roleList_dept'
            , type: 'post'
            , dataType: 'json'
            , contentType: "application/json; charset=utf-8"
            , data: JSON.stringify(delId)
            , done: function (res) {
                if (res.data.length == 0) {
                    $("#system").val(obj.data.systemname)
                    $.ajax({
                        url: setter.host + '/unite_platform/goods_order/getsystemInfo?id=' + id + '&goodscode=' + goodscode,
                        type: 'get',
                        contentType: "application/json; charset=utf-8",
                        dataType: 'json',
                        success: function (res) {
                            showdiv()
                            if (res.status == setter.response.statusCode.status_Success) {
                                if (res.data.id[0] == undefined) {
                                    $("#orderType").val('');
                                    $("#ordernum").val('');
                                    $("#oplvalue").val('');
                                    $("#orderintype").val('');
                                    $("#safestock").val('');
                                    $("#startdateLayDate").val('');
                                    $("#enddateLayDate").val('');
                                    $("#minday").val('');
                                    $("#attribute").val('');
                                    $("#flag").val('');
                                    $("#remark").val('');
                                } else {
                                    $("#orderType").val(res.data.id[0].orderType);
                                    $("#ordernum").val(res.data.id[0].ordernum);
                                    $("#oplvalue").val(res.data.id[0].oplvalue);
                                    $("#orderintype").val(res.data.id[0].orderintype);
                                    $("#safestock").val(res.data.id[0].safestock);
                                    $("#startdateLayDate").val(res.data.id[0].startdate);
                                    $("#enddateLayDate").val(res.data.id[0].enddate);
                                    $("#minday").val(res.data.id[0].minday);
                                    $("#attribute").val(res.data.id[0].attribute);
                                    $("#flag").val(res.data.id[0].flag);
                                    $("#remark").val(res.data.id[0].remark);
                                    form.render();
                                    // layer.msg(res.msg);
                                }
                            }
                        }
                    });
                } else {
                    hiddendiv();
                }
            }
        });

        var classcode;
        $("#tableDelete").on("click", function () {
            classcode = obj.data.classcode;
            layer.open({
                content: '是否删除？'
                , btn: ['是', '否']
                , yes: function (index, layero) {
                    $.ajax({
                        url: setter.host + '/unite_platform/goods_class/deleteGoods?classcode=' + classcode,
                        type: 'get',
                        contentType: "application/json; charset=utf-8",
                        data: {},
                        dataType: 'json',
                        success: function (res) {
                            //请求成功后
                            if (res.status == setter.response.statusCode.status_Success) {
                                layer.msg(res.msg);
                            } else {
                                layer.msg(res.msg);
                            }
                        }
                    });
                }
                , btn3: function (index, layero) {
                    return false;
                }
                , cancel: function () {
                    return false;
                }
            });
        })
        var system;
        var orderType;
        var ordernum;
        var oplvalue;
        var orderintype;
        var safestock;
        var startdate;
        var enddate;
        var minday;
        var attribute;
        var flag;
        var remark;
        var xgr;


        $("#tableInsert").on("click", function () {

            $("#fatherclassname").attr("readonly", false);
            $("#classcode").attr("readonly", false);
            fatherclassname = $("#classname").val();
            $("#fatherclassname").val($("#classname").val());
            fatherclasscode = $("#classcode").val();
            $("#fatherclasscode").val($("#classcode").val());
            $("#fatherclassname").attr("readonly", true);
            $("#fatherclasscode").attr("readonly", true);
            $("#classcode").val("");
            $("#classname").attr("readonly", false);
            $("#classname").val("");
            $("#classremark").attr("readonly", false);
            $("#classremark").val("");
            dateType = $("#tableInsert").attr("data-type");
        })
        $("#tableEdit").on("click", function () {
            $("#classname").attr("readonly", false);
            $("#classremark").attr("readonly", false);
            dateType = $("#tableEdit").attr("data-type");
        })
    });


    treeTable.on('row(LAY-role-list)', function (obj) {
        id = obj.data.id;
        var delId = {};
        delId.id = obj.data.id;
        layui.admin.req({
            url: layui.setter.host + '/goods_system_supplier/roleList_dept'
            , type: 'post'
            , dataType: 'json'
            , contentType: "application/json; charset=utf-8"
            , data: JSON.stringify(delId)
            , done: function (res) {
                if (res.data.length == 0) {
                    $("#system").val(obj.data.name)
                    $.ajax({
                        url: setter.host + '/unite_platform/goods_order/getsystemInfo?id=' + id + '&goodscode=' + goodscode,
                        type: 'get',
                        contentType: "application/json; charset=utf-8",
                        dataType: 'json',
                        success: function (res) {
                            showdiv()
                            if (res.status == setter.response.statusCode.status_Success) {
                                if (res.data.id[0] == undefined) {
                                    $("#orderType").val('');
                                    $("#ordernum").val('');
                                    $("#oplvalue").val('');
                                    $("#orderintype").val('');
                                    $("#safestock").val('');
                                    $("#startdateLayDate").val('');
                                    $("#enddateLayDate").val('');
                                    $("#minday").val('');
                                    $("#attribute").val('');
                                    $("#flag").val('');
                                    $("#remark").val('');
                                } else {
                                    $("#orderType").val(res.data.id[0].orderType);
                                    $("#ordernum").val(res.data.id[0].ordernum);
                                    $("#oplvalue").val(res.data.id[0].oplvalue);
                                    $("#orderintype").val(res.data.id[0].orderintype);
                                    $("#safestock").val(res.data.id[0].safestock);
                                    $("#startdateLayDate").val(res.data.id[0].startdate);
                                    $("#enddateLayDate").val(res.data.id[0].enddate);
                                    $("#minday").val(res.data.id[0].minday);
                                    $("#attribute").val(res.data.id[0].attribute);
                                    $("#flag").val(res.data.id[0].flag);
                                    $("#remark").val(res.data.id[0].remark);
                                    form.render();
                                    // layer.msg(res.msg);
                                }
                            }
                        }
                    });
                } else {
                    hiddendiv();
                }
            }
        });

        var classcode;
        $("#tableDelete").on("click", function () {
            classcode = obj.data.classcode;
            layer.open({
                content: '是否删除？'
                , btn: ['是', '否']
                , yes: function (index, layero) {
                    $.ajax({
                        url: setter.host + '/unite_platform/goods_class/deleteGoods?classcode=' + classcode,
                        type: 'get',
                        contentType: "application/json; charset=utf-8",
                        data: {},
                        dataType: 'json',
                        success: function (res) {
                            //请求成功后
                            if (res.status == setter.response.statusCode.status_Success) {
                                layer.msg(res.msg);
                            } else {
                                layer.msg(res.msg);
                            }
                        }
                    });
                }
                , btn3: function (index, layero) {
                    return false;
                }
                , cancel: function () {
                    return false;
                }
            });
        })
        var system;
        var orderType;
        var ordernum;
        var oplvalue;
        var orderintype;
        var safestock;
        var startdate;
        var enddate;
        var minday;
        var attribute;
        var flag;
        var remark;
        var xgr;


        $("#tableInsert").on("click", function () {

            $("#fatherclassname").attr("readonly", false);
            $("#classcode").attr("readonly", false);
            fatherclassname = $("#classname").val();
            $("#fatherclassname").val($("#classname").val());
            fatherclasscode = $("#classcode").val();
            $("#fatherclasscode").val($("#classcode").val());
            $("#fatherclassname").attr("readonly", true);
            $("#fatherclasscode").attr("readonly", true);
            $("#classcode").val("");
            $("#classname").attr("readonly", false);
            $("#classname").val("");
            $("#classremark").attr("readonly", false);
            $("#classremark").val("");
            dateType = $("#tableInsert").attr("data-type");
        })
        $("#tableEdit").on("click", function () {
            $("#classname").attr("readonly", false);
            $("#classremark").attr("readonly", false);
            dateType = $("#tableEdit").attr("data-type");
        })
    });


    var active = {
        backtable: function () {
            hiddendiv();
        },
        save: function () {
            form.on('submit(save)', function (data) {
                var field = data.field;
                console.log(id)
                var modifyUrL = layui.setter.host + '/goods_order/edit';

                system = id;
                orderType = $("#orderType").val();
                if (orderType==null||orderType==undefined){
                    orderType = "0";
                }
                ordernum = $("#ordernum").val();
                oplvalue = $("#oplvalue").val();
                autoorder = '0';

                orderintype = $("#orderintype").val();
                if (orderintype==null||orderintype==undefined){
                    orderintype = "1";
                }
                safestock = $("#safestock").val();
                minday = $("#minday").val();
                startdate = $("#startdateLayDate").val();
                enddate = $("#enddateLayDate").val();
                attribute = $("#attribute option:selected").val();
                flag = $("#flag option:selected").val();
                remark = $("#remark").val();

                var json = {
                    'goodscode': goodscode,
                    'system': id,
                    'ordertype': orderType,
                    'ordernum': ordernum,
                    'oplvalue': oplvalue,
                    'autoorder': "0",
                    'orderintype': orderintype,
                    'safestock': safestock,
                    'minday': minday,
                    'startdate': startdate,
                    'enddate': enddate,
                    'attribute': attribute,
                    'flag': flag,
                    'remark': remark
                }

                layui.admin.req({
                    url: modifyUrL
                    , type: 'post'
                    , dataType: 'json'
                    , contentType: "application/json; charset=utf-8"
                    , data: JSON.stringify(json)
                    , success: function (res) {
//						console.log(res);
                        //请求成功后
                        if (res.status == setter.response.statusCode.status_Success) {
                            layer.msg(res.msg);
                        } else {
                            layer.msg(res.msg);
                        }
                    }

                });
            });
            $('[lay-filter="save"]').trigger('click');
        }
    }


    $('.layui-btn').on('click', function () {
        var type = $(this).data('type');
        active[type] ? active[type].call(this) : '';
    });


    exports('insert2', obj);
});

